package common.splitpage;

public class PageHelper {
	protected int rowCount;//总记录数
	protected int pageSize;//页大小
	protected int pageNum;//当前页码

	protected int startRow;
	protected int endRow;

	public PageHelper(int rowCount, int pageSize, int pageNum) {
		this.rowCount = rowCount;
		this.pageSize = pageSize;
		this.pageNum = pageNum;
		
		setPageRows();
	}
	
	public int getStartRow() {
		return this.startRow;
	}
	
	public int getEndRow() {
		return this.endRow;
	}

	// 返回总页数
	public int getPageCount() {
		if (rowCount == 0) {
			return 0;
		}
		if (pageSize == 0) {
			return 1;
		}
		// calculate PageCount
		double doublePages = (double) rowCount / pageSize;
		int intPages = (int) doublePages;
		if (doublePages > intPages) { // 有余数
			intPages += 1;
		}
		return intPages;
	}

	// 返回当前页的记录条数
	public int getPageRowCount() {
		if (rowCount == 0) {
			return 0;
		}
		if (pageNum != getPageCount()) {// 不是最后一页
			return pageSize;
		}
		// 最后一页的记录数小于等于pageSize
		return rowCount - (this.getPageCount() - 1) * pageSize;
	}

	// 设置指定页的开始行和结束行
	private void setPageRows() {
		int pageCount = this.getPageCount();
		if(pageCount == 0) {
			pageNum = 1;
			this.startRow = 0;
			this.endRow = 0;
		} else {
			if (pageNum < 1) {
				pageNum = 1;
			}
			if (pageNum > pageCount) {
				pageNum = pageCount;
			}
	
			int startRow = (pageNum - 1) * pageSize + 1;
			int endRow = startRow + pageSize - 1;
			if (pageNum == pageCount) {
				endRow = rowCount;
			}
	
			this.startRow = startRow;
			this.endRow = endRow;
		}
	}
	
	public void pageFirst() {
		this.pageNum = 1;
		this.setPageRows();
	}

	public void pageLast() {
		this.pageNum = this.getPageCount();
		this.setPageRows();
	}

	public void pageNext() {
		this.pageNum = this.pageNum + 1;
		this.setPageRows();
	}

	public void pagePrevious() {
		this.pageNum = this.pageNum - 1;
		this.setPageRows();
	}

}
